package com.example.aircraftwar.codes.activity;

import androidx.appcompat.app.AppCompatActivity;
import com.example.aircraftwar.R;
import com.example.aircraftwar.codes.goal2.Record2;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class LoginActivity extends AppCompatActivity {
    private EditText Name, Password;
    private List<Record2> records = new ArrayList<>();
    private SharedPreferences sp;
    //private SharedPreferences.Editor editor;
    private boolean isExist;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Name = findViewById(R.id.name);
        Password = findViewById(R.id.password);
    }

    public void login(View view) {
        String sName = Name.getText().toString();
        String sPassword = Password.getText().toString();
        initRecords();
        isExist = false;
        for(Record2 instance:records){
            if(Objects.equals(instance.getName(), sName) && Objects.equals(instance.getPassword(), sPassword)){
                isExist = true;
                //System.out.println("Success!");
                break;
            }
        }
        if(isExist){
            enterGame();
        }else{
            Toast toast=Toast.makeText(this,"出现错误，账号或密码错误！",Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER,0,50);
            toast.show();
        }
    }

    public void reg(View view){
        Intent intent = new Intent();
        intent.setClass(this,RegActivity.class);
        startActivity(intent);
    }

    private void enterGame(){
        Intent intent = new Intent();
        intent.setClass(this,OptActivity.class);
        startActivity(intent);
    }

    private void initRecords(){
        sp = getSharedPreferences("account",MODE_PRIVATE);
        String goals_json = sp.getString("goals2",null);
        if(null == goals_json){
            records.clear();
            //System.out.println("//？？？//");
        } else {
            Gson gson = new Gson();
            records = gson.fromJson(goals_json,new TypeToken<List<Record2>>(){}.getType());
            /*for (Record2 instance:records){
                System.out.println(instance.getName()+" - "+instance.getPassword());
            }*/
        }
    }

}